
var win = null;
var cvs = null;
var ctx = null;
var isDraw = false;
var lastX = 0;
var lastY = 0;
var strokeColor = 'black';
var lineWidth = 1;


function main (evt) {
    win = window;
    cvs = document.getElementById('canvas');
    ctx = cvs.getContext('2d');
    if (!ctx) {
        return;
    }
    cvs.width = W = win.innerWidth;
    cvs.height = H = win.innerHeight;

    cvs.addEventListener('mousedown', function (evt) {
        evt = evt || window.evt;
        startDraw(evt.clientX, evt.clientY);
    });

    cvs.addEventListener('mousemove', function (evt) {
        evt = evt || window.evt;
        draw(evt.clientX, evt.clientY);
    });

    cvs.addEventListener('mouseup', function (evt) {
        stopDraw();
    });

    cvs.addEventListener('touchstart', function (evt) {
        evt = evt || window.evt;
        startDraw(evt.touches[0].clientX, evt.touches[0].clientY);
    });

    cvs.addEventListener('touchmove', function (evt) {
        evt = evt || window.evt;
        evt.preventDefault();
        // evt.stopPropagation();
        draw(evt.touches[0].clientX, evt.touches[0].clientY);
    });

    cvs.addEventListener('touchend', function (evt) {
        stopDraw();
    });

    var btnNew = document.getElementById('new');
    btnNew.addEventListener('click', function (evt) {
        clearCanvas();
    });

    var btnColor = document.getElementById('color');
    var colorSelector = new ColorSelector();
    var btnPen = document.getElementById('pen');
    var penSelector = new PenSelector();

    colorSelector.init(document.getElementById('color-selector'));
    colorSelector.onItemClick = function (color) {
        strokeColor = color;
    }
    btnColor.addEventListener('click', function (evt) {
        penSelector.hide();
        colorSelector.show();
    });

    penSelector.init(document.getElementById('pen-selector'));
    penSelector.onItemClick = function (size) {
        lineWidth = size;
    }
    btnPen.addEventListener('click', function (evt) {
        colorSelector.hide();
        penSelector.show();
    });
}


function startDraw (x, y) {
    isDraw = true;
    lastX = x;
    lastY = y;
}


function draw (x, y) {
    if (isDraw) {
        ctx.beginPath();
        ctx.lineWidth = lineWidth;
        ctx.lineCap = 'round';
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
        // ctx.strokeStyle = rgba(0, 0, 0, 0.5 + Math.random());
        // ctx.closePath();     // closePath 使得 lineCap 不起作用
        ctx.strokeStyle = strokeColor;
        ctx.stroke();
        lastX = x;
        lastY = y;
    }
}


function stopDraw () {
    isDraw = false;
}


function clearCanvas () {
    ctx.clearRect(0, 0, cvs.width, cvs.height);
}

function rgba (red, green, blue, alpha) {
    red = parseInt(red);
    green = parseInt(green);
    blue = parseInt(blue);
    return 'rgba(' + red + ', ' + green + ', ' + blue + ', ' + alpha + ')';
}

window.addEventListener('load', main);
